package upicgame.user.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import upicgame.entity.User;
import upicgame.user.service.UserService;
import upicgame.utils.VerifyCode;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @program: upicgame
 * @description: 用户管理控制器
 * @author: lhq
 * @create: 2019-12-17 15:08
 */
@Controller
public class UserController {
	@Resource
	UserService userService;


	@RequestMapping(value = "addUser",produces = "text/html; charset=utf-8")
	@ResponseBody
	public String addUser(User user){
		user.setUserType("user");
		System.out.println(user);
		boolean addUser = userService.addUser(user);
		System.out.println("执行了addUser");
		if (addUser){
			return "用户"+user.getName()+"添加成功";
		}else {
			return "添加失败";
		}

	}
	@RequestMapping(value = "updateUser")
	public String updateUserInfo(HttpServletRequest request,
							   Model model,
							   @RequestParam("upload") MultipartFile upload,
							   @RequestParam("id") Integer id,
							   @RequestParam("name") String name,
							   @RequestParam("password") String password,
							   @RequestParam(value = "userType",required = false) String userType,
							   @RequestParam("address") String address,
							   @RequestParam("email") String email
							   ) throws IOException {
		System.out.println("测试文件上传________");
		User user = userService.findUser(id,"id");
		/**
		 * 优化上传逻辑
		 * 如果上传文件为空
		 * 则不进行上传文件操作,只更改其他部分
		 */
		if( !upload.isEmpty() ) {
			String filename = upload.getOriginalFilename();
			String path = request.getSession().getServletContext().getRealPath("upload");
			File file = new File(path);
			if (!file.exists()){
				file.mkdirs();
			}
			if(filename == null){
				System.out.println("无法获取头像文件名");
			}else {
				upload.transferTo(new File(path,filename));
				System.out.println(path);
				System.out.println(filename);
				user.setImg(filename);
			}
		}
		user.setName(name);
		user.setPassword(password);
		if (userType!=null){
			user.setUserType(userType);
		}
		user.setAddress(address);
		user.setEmail(email);

		System.out.println(user);
		boolean updateUser = userService.updateUser(user);
		model.addAttribute("user",user);
		if ("admin".equals(user.getUserType())){
			return "redirect:userList.html";
		}else {
			return "redirect:index.jsp";
		}
	}


	@RequestMapping(value = "showUserInfo")
	public ModelAndView showUserInfo(Integer id){
		ModelAndView mv = new ModelAndView();
		User user = userService.findUser(id,"id");
		mv.addObject("user",user);
		mv.setViewName("showUserInfo.jsp");
		return mv;
	}
	@RequestMapping(value = "showUserInfoAdmin")
	public ModelAndView showUserInfoAdmin(Integer id){
		ModelAndView mv = new ModelAndView();
		User user = userService.findUser(id,"id");
		mv.addObject("user",user);
		mv.setViewName("showUserInfoAdmin.jsp");
		return mv;
	}


	@RequestMapping(value = "deleteUser")
	public ModelAndView deleteUser(Integer id){
		//to-do
		ModelAndView modelAndView = new ModelAndView();
		boolean deleteUser = userService.deleteUser(id);
		modelAndView.setViewName("userList.html");
		return modelAndView;
	}

	@RequestMapping(value = "userList",produces = "application/json; charset=UTF-8")
	@ResponseBody
	public List<User> userList(Integer pageNum,Integer size){
		System.out.println("pageNum:"+pageNum+"____"+"size:"+size);
		pageNum = pageNum == null ? 1:pageNum;
		List<User> userList = userService.userLit(pageNum,size);
		String json = JSON.toJSONString(userList);
		System.out.println(json);
		return userList;
	}
	@RequestMapping(value = "login")
	public String login(HttpServletRequest request,
							  @RequestParam(value = "verifyCode",required = false) String verifyCode,
							  @RequestParam(value = "username",required = false) String username,
							  @RequestParam(value = "password",required = false) String password){

		String verifyText = (String) request.getSession().getAttribute("verifyText");
		User user = userService.login(username,password);
		if (verifyText != null && verifyText.equalsIgnoreCase(verifyCode) && user != null){
			request.getSession().setAttribute("user",user);
		}else {
				System.out.println("验证码错误或密码错误");
				return "forward:login_register.jsp";
			}
		if ("admin".equals(user.getUserType())){
			return "forward:admin.jsp";
		}
		return "redirect:index.jsp";

	}
	@RequestMapping(value = "register")
	public ModelAndView register(HttpServletRequest request,
						 @RequestParam(value = "verifyCode",required = false) String verifyCode,
						 User user){
		String verifyText = (String) request.getSession().getAttribute("verifyText");
		ModelAndView modelAndView = new ModelAndView();
		user.setImg("default.jpg");
		modelAndView.setViewName("login_register.jsp");
		if( verifyText != null && verifyText.equalsIgnoreCase(verifyCode)){
			user.setUserType("user");
			System.out.println(user);
			if (userService.addUser(user)){
				modelAndView.addObject("msg","注册成功请登录");

				return modelAndView;
			}
		}else {
			modelAndView.addObject("msg","注册失败请从新注册");
		}
		return modelAndView;

	}
	@RequestMapping(value = "count")
	@ResponseBody
	public Long getCount(){
		return  userService.totalCount();
	}
	@RequestMapping(value = "addMoney")
	public ModelAndView addMoney(HttpServletRequest request,Integer id,Double money){
		ModelAndView modelAndView = new ModelAndView("addMoney.jsp");
		if(id != null && money != null && money>=0){
			System.out.println("充钱ID:"+id);
			System.out.println("充钱金额:"+money);
			User user = userService.addMoney(id,money);
			request.getSession().setAttribute("user",user);
			System.out.println("氪金成功!");
		}else {
			System.out.println("没有氪金");
			modelAndView.addObject("msg","充值金额不能为空或负数");
			return modelAndView;
		}
		return modelAndView;
	}

	/**
	 * 用户登出清除session
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "logout")
	public String loginOut( HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("user");
		System.out.println(user);
		request.getSession().removeAttribute("user");
		User user1 = (User) request.getSession().getAttribute("user");
		System.out.println(user1);
		return "index.jsp";
	}
	@RequestMapping(value = "verifyCode")
	@ResponseBody
	public void verifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		VerifyCode verifyCode = new VerifyCode();
		BufferedImage buffImage = verifyCode.getImage();
		String verifyText = verifyCode.getText();
		request.getSession().setAttribute("verifyText",verifyText);
		VerifyCode.output(buffImage,response.getOutputStream());
	}
}
